package com.wanmait.zaisousuo.webcontroller;

import com.github.pagehelper.PageInfo;
import com.wanmait.zaisousuo.pojo.Answer;
import com.wanmait.zaisousuo.pojo.Userinfo;
import com.wanmait.zaisousuo.service.AnswerService;
import com.wanmait.zaisousuo.service.QuestionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/web")
public class AnswerWebController {
    @Resource
    private AnswerService answerService;
    @Resource
    private QuestionService questionService;
//    更新问题以及回答状态
    @RequestMapping("/answer/finished")
    @ResponseBody
    public void answeFinished(Answer answer){
        questionService.clearCache();//清除问答的cache
        answerService.answerAccepted(answer);
    }

//    获取回答
    @RequestMapping("question/answerData")
    public ModelAndView answerData(Integer pageNum,Integer questionId,HttpServletRequest request,boolean finished,Integer userinfoId){
        ModelAndView mv = new ModelAndView();
        PageInfo<Answer> pageInfo = answerService.findByQuestionId(questionId,pageNum);
        mv.addObject("userinfoId",userinfoId);
        mv.addObject("finished",finished);
        mv.addObject("pageInfo",pageInfo);
        return mv;
    }
//    添加回答
    @RequestMapping("answer/insert")
    public String insert(Answer answer, HttpServletRequest request){
        questionService.clearCache();//清除问答的cache
        Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");

        answer.setUserinfo(userinfo);
        String path = request.getHeader("referer");
        answerService.insert(answer);
        return "redirect:"+path;
    }
}